from fastapi import Request

from service import UserService, SongService
from common.result.Result import Result
from common.enum import BaseEnum
from util.log import Log
from util.token import Token
from util.str import Str

async def GetSongListBySheetId(req: Request, sheetId: str):
    try:
        token = req.headers.get("token")
        user = await UserService.getUserByToken(token)
        
        sheet = await SongService.getSheetById(sheetId)
        if sheet == None:
            return Result.error(BaseEnum.SONG_SHEET_NOT_EXIST_ERROR)
    
        # 获取 该歌单 的收藏记录
        favoriteList = await SongService.getFavoriteListBySheetId(sheet.id)
        songIdList = [item.song_id for item in favoriteList]
        # 通过 收藏记录 获取 song 列表
        songList = await SongService.getSongListByIdList(songIdList)

        res = [dict(song) for song in songList]

        if user != None:
            iLikeSongList = await SongService.getILikeSongList(user.id)
            for song in res:
                for like in iLikeSongList:
                    if song.get("id") == like.id:
                        song.update(isFavorite=True)

        return Result.success(res)
    except Exception as e:
        Log.error('获取 sheet 中的 song 列表异常', e)
        return Result.error(BaseEnum.SERVICE_ERROR)